package com.sks.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sks.bean.pojo.SysInfo;
import com.sks.bean.privilege.Employee;
import com.sks.core.SystemConstants;
import com.sks.service.base.SysInfoService;
import com.sks.utils.StringUtil;
import com.sks.utils.WebAppContextUtil;
import com.sks.utils.WebUtil;

public class InternalFilter implements Filter {
   
   private SysInfoService sysInfoService;
   
   private String excludeUrlPattern;

   @Override
   public void destroy() {

   }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response,
         FilterChain chain) throws IOException, ServletException {
      HttpServletRequest req = (HttpServletRequest) request;
      
      if (null != excludeUrlPattern) {
         String[] patterns = excludeUrlPattern.split(",");
         String uri = req.getRequestURI();
         for (String pattern : patterns) {
            if (StringUtil.matchURLByTomcat(pattern, uri)) {
               chain.doFilter(request, response);
            }
         }
      }
      
      Employee employee = WebUtil.getEmployee(req);
      if (employee == null) {// 如果员工未登录，重定向到员工登陆界面
         HttpServletResponse res = (HttpServletResponse) response;
         res.sendRedirect("/com/sks/privilege/employee/logon.do");
      } else {
         chain.doFilter(request, response);
      }
   }

   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
      
      String temp = filterConfig.getServletContext().getRealPath("/");
      SysInfo si = sysInfoService.get(SystemConstants.SYS_INFO_KEY_UPLOAD_FILE_DIR);
      if (null == si) {
         si = new SysInfo(SystemConstants.SYS_INFO_KEY_UPLOAD_FILE_DIR, temp);
         sysInfoService.save(si);
      } else {
    	 si.setValue(temp);
    	 sysInfoService.update(si);
      }
      
      WebAppContextUtil.init(filterConfig.getServletContext());
   }

   public String getExcludeUrlPattern() {
      return excludeUrlPattern;
   }

   public void setExcludeUrlPattern(String excludeUrlPattern) {
      this.excludeUrlPattern = excludeUrlPattern;
   }

   public SysInfoService getSysInfoService() {
      return sysInfoService;
   }

   public void setSysInfoService(SysInfoService sysInfoService) {
      this.sysInfoService = sysInfoService;
   }

}
